package com.kl.listen;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Map;

@Component
public class ApplicationStartup  implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        //获取使用指定Annotation的bean,这里是Configuration
        Map<String,Object> map = event.getApplicationContext().getBeansWithAnnotation(Configuration.class);
        for(Object bean : map.values()){
            System.out.println("bean的类名 = "+bean.getClass().getName());
        }

        //指定类
        User user = event.getApplicationContext().getBean(User.class);
        System.out.println("获取指定类的类名 = " + user.getClass().getName());

        //发布事件
        User test = new User();
        test.setName("test");
        event.getApplicationContext().publishEvent(test);
    }
}

@Service
class EventTest{

    /**
     * 监听事件
     */
    @EventListener
    public void placeOrderNotice(User user) {
        System.out.println("name:"+user.getName());
    }
}

/**
 * 需要使用@Configuration 或者 @Component,否则无法getBean
 */
@Configuration
class User{
    String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
